package com.isunland.managesystem.base;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import com.isunland.managesystem.R;
import com.isunland.managesystem.utils.LocalSearch;
import java.util.ArrayList;

/**
 * 对象功能: 基础搜索类,可以继承来集成搜索和多选功能.
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 3/30/2017 11:11 AM
 */

public abstract class BaseMultiSearchListFragment<T> extends BaseListFragment {

  //public static final String EXTRA_LIST= "com.isunland.managesystem.base.BaseSearchListFragment.EXTRA_LIST";
  protected ArrayList<T> mList;//当前数据
  protected ArrayList<T> mListOriginal;//全部数据
  protected ArrayList<T> mListTemp;//临时数据.
  //protected EditText mSearchEt;
  private BaseMultiChoiceAdapter<T> mAdapter;
  /**
   * 是否已全选
   */
  private boolean isSelectedAll;
  private Menu mMenu;
  /** 是否重新创建适配器 */
  private boolean isRecreate;
  private SearchAsyncTask mSearchAsyncTask;

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mList = new ArrayList<>();
    mListOriginal = new ArrayList<>();
    mListTemp = new ArrayList<>();
    mSearchAsyncTask = new SearchAsyncTask();
  }

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    //mListview.setDivider(null);
    //View header =
    //    getLayoutInflater(savedInstanceState).inflate(R.layout.header_search_person, mListview,
    //        false);
    //mSearchEt = (EditText) header.findViewById(R.id.et_search_searchPersonHeader);
    //mSearchEt.setHint(R.string.inputSearchContent);
    //mSearchEt.addTextChangedListener(new TextWatcher() {
    //
    //  @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
    //    if (search(s)) return;
    //    mSearchEt.requestFocus();
    //  }
    //
    //  @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    //
    //  }
    //
    //  @Override public void afterTextChanged(Editable s) {
    //
    //  }
    //});
    //mListview.addHeaderView(header);
    //setAdapter();
  }

  private void search(CharSequence s) {
    if (mListOriginal == null || mListOriginal.size() == 0) return;
    if (TextUtils.isEmpty(s)) {
      mListTemp = mListOriginal;
      return;
    }
    mListTemp = LocalSearch.search(s.toString(), mListOriginal, setQueryField());
  }

  /**
   * 设置可搜索字段
   *
   * @return 可搜索字段,
   */
  protected abstract String[] setQueryField();

  protected void setAdapter() {
    if (mListTemp == null) return;
    mList.clear();
    mList.addAll(mListTemp);
    //全部数据有变化时是接口有返回数据,这时需要更新adapter.
    if (mAdapter == null || isRecreate) {
      /** 如果原始数据为空,下次还需要重新创建*/
      isRecreate = (mListOriginal == null) || (mListOriginal.size() == 0);
      mAdapter = initAdapter();
      setListAdapter(mAdapter);
    }
    ((BaseMultiChoiceAdapter) getListAdapter()).notifyDataSetChanged();
  }

  @NonNull protected abstract BaseMultiChoiceAdapter<T> initAdapter();

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case R.id.menu_item_confirm:
        if (mListOriginal == null || mAdapter == null) return false;

        Intent i = getSelectIntent(mAdapter.getCheckedItems());
        getActivity().setResult(Activity.RESULT_OK, i);
        getActivity().finish();
        return true;
      //全选
      case R.id.menu_item_bat:
        //如果网络请求未完成,adapter==null.
        if (mAdapter == null) return false;
        if (isSelectedAll) {
          //当前状态为已全选,点击按钮,执行反选.
          mAdapter.deSetlectAll();
          isSelectedAll = false;
          mMenu.findItem(R.id.menu_item_bat).setIcon(R.drawable.bat);
          mMenu.findItem(R.id.menu_item_bat).setTitle(R.string.selectAll);
        } else {
          //默认未全选.执行全选.并更新按钮状态为已全选,按钮为取消全选.
          mAdapter.setlectAll();
          isSelectedAll = true;
          mMenu.findItem(R.id.menu_item_bat).setIcon(R.drawable.cancle);
          mMenu.findItem(R.id.menu_item_bat).setTitle(R.string.deselectAll);
        }

        break;
      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  @NonNull protected abstract Intent getSelectIntent(ArrayList<T> selectList);

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    //        inflater.inflate(R.menu.menu_confirm, menu);
    inflater.inflate(R.menu.menu_multi_search_confirm, menu);
    mMenu = menu;
    MenuItem menuItem = menu.findItem(R.id.menu_item_search);//在菜单中找到对应控件的item
    final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
    //android.support.v7.widget.SearchView.setOnQueryTextListener
    if (searchView == null) return;
    //searchView.setQueryHint(getString(R.string.inputSearchContent));
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
      @Override public boolean onQueryTextSubmit(String query) {
        //ToastUtil.show("提交:"+query);
        return false;
      }

      @Override public boolean onQueryTextChange(String newText) {
        //一个任务只能执行一次.
        mSearchAsyncTask.cancel(true);
        mSearchAsyncTask = new SearchAsyncTask();
        mSearchAsyncTask.execute(newText);
        showLoading(true);
        return true;
      }
    });

    super.onCreateOptionsMenu(menu, inflater);
  }

  //三个类型依次为,参数,进度,返回值.
  private class SearchAsyncTask extends AsyncTask<CharSequence, Void, Void> {
    //后台任务执行的地方.
    protected Void doInBackground(CharSequence... s) {
      if (s == null || s.length == 0) return null;
      search(s[0]);
      return null;
    }

    protected void onPostExecute(Void result) {
      showLoading(false);
      setAdapter();
    }
  }
}
